package com.jtcoding.chat.controller;

import com.jtcoding.chat.model.FastDFSResource;
import com.jtcoding.chat.model.ResourceLog;
import com.jtcoding.chat.model.Result;
import com.jtcoding.chat.service.ResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author jason.tang
 * @create 2019-01-25 16:46
 * @description 资源控制层
 */
@Api(tags = "资源相关")
@RestController
@RequestMapping("/resources")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @ApiOperation(value = "获取历史资源列表", notes = "获取历史资源列表")
    @GetMapping("/histories/{refNum}/{resType}")
    public Result<List<ResourceLog>> getHistoryResource(@PathVariable Integer refNum, @PathVariable String resType) {
        return Result.success(resourceService.getHistoryResource(refNum, resType));
    }

    @ApiOperation(value = "删除某个历史记录", notes = "删除某个历史记录")
    @DeleteMapping("/histories/{groupName}/{remoteFileName}")
    public Result<Boolean> deleteHistoryRes(@PathVariable String groupName, @PathVariable String remoteFileName) throws IOException, MyException {
        return Result.success(resourceService.deleteResource(groupName, remoteFileName));
    }

    @ApiOperation(value = "上传Base64二进制加密文件", notes = "上传Base64二进制加密文件")
    @PostMapping("/upload")
    public Result<?> uploadBinaryFile(@RequestParam("file") MultipartFile file) throws IOException, MyException {
        byte[] bytes = file.getBytes();
        FastDFSResource resource = new FastDFSResource();
        resource.setName(file.getOriginalFilename());
        resource.setContent(bytes);
        resource.setFromService("CHAT");
        resource.setResType("CHAT");
        resource.setRefNum(1);
        return Result.success(resourceService.uploadResource(resource));
    }
}